package com.zm.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;

public class Md5 {

    final static String token_key = "UH9IE73TXZK0H2A16A1M8N6B1AH2A1P2";

    public String getDateToken() {

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = sDateFormat.format(new java.util.Date());
        String dateMd5 = stringToMD5(date);

        String all = dateMd5 + token_key;
        String allMd5 = stringToMD5(all);

        return allMd5;
    }

    public String getUidToken(String Uid) {

        String dateMd5 = stringToMD5(Uid);
        String all = dateMd5 + token_key;
        String allMd5 = stringToMD5(all);
        return allMd5;
    }

    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    /**
     * md5中的字母转换成数字
     *
     * @param string
     * @return
     */
    public static String md5StringToNum(String string) {

        return string.toLowerCase()
                .replace("a", "10")
                .replace("b", "11")
                .replace("c", "12")
                .replace("d", "13")
                .replace("e", "14")
                .replace("f", "15");
    }

    /**
     * 字符串加密成纯数字
     * @param str
     * @return
     */
    public static String stringToMD5PureNum(String str) {
        return md5StringToNum(stringToMD5(str));
    }

    public static String shaEncrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
